package Server;

/**
 *
 * @author Daniel
 */
import java.net.*;
import java.io.*;
import java.util.ArrayList;

public class Server
{
    //Holds the server port
    private ServerSocket connection = null;
    static BookStoreDB bsd=null;
    ArrayList<Client> clientList = new ArrayList<Client>();
    //Clients ID
    private int clients             = 0;

    //Server constructor, must specify a port number!!
    public Server(int port)
    {
        //Construct
        System.out.println("Attempting to initialize server...");

        //Try to create the server socket, then print out the server address
        try
        {
            this.connection    = new ServerSocket(port);
            System.out.println("I am: " + this.connection.getInetAddress().getHostName());
        }
        catch(Exception e)
        {
            System.out.println("Server init failed.");
            System.out.println("Error: " + e);
            System.exit(1);
        }

        //Confirmation that server interface is up
        System.out.println("Server up");

        System.out.println("Loading Customers, Books and Orders Into The System");

        bsd = new BookStoreDB();
        //bsd.showBooks();

    }

    //Listen method, continuous loop to create new Client objects
    public void listen() throws IOException {
        System.out.println("Listening...");

        //Continously loop
        //TODO: add the ability to escape and cleanly terminate program
        while(true){

                //Create a new client object, pass the incoming connection and client count
                Client client = new Client(this.connection.accept(), clients++);
                //We want to print out where the connection came from
                //System.out.println(client.getSocket().getLocalAddress().getHostName() + " connected, count "+ clients);
             //Listening again
                //System.out.println("Listening...");
        }

    }
}